#include <assert.h>
#include <stdlib.h>
#include "cue.h"

void
fill_cue_cdtime(struct cue_cdtime *cdtime, int mins, int secs, int frames)
{
	assert(cdtime != NULL);

	cdtime->mins = mins;
	cdtime->secs = secs;
	cdtime->frames = frames;
}

struct cue_track_part *
create_cue_track_part()
{
	struct cue_track_part *result = calloc(1, sizeof(struct cue_track_part));
	assert(result != NULL);
	return result;
}

void
destroy_cue_track_part(struct cue_track_part *part)
{
	free(part->filepath);
	free(part);
}

struct cue_track *
create_cue_track()
{
	struct cue_track *result = calloc(1, sizeof(struct cue_track));
	assert(result != NULL);
	return result;
}

void
destroy_cue_track(struct cue_track *track)
{
	int i;

	free(track->songwriter);
	free(track->performer);
	free(track->title);
	for (i = 0; i < track->parts_count; ++i)
		destroy_cue_track_part(track->parts[i]);
	free(track->parts);
	free(track);
}

int
add_cue_track_part(struct cue_track *track, struct cue_track_part *part)
{
	assert(track != NULL);
	assert(part != NULL);

	++track->parts_count;
	++track->parts_size;

	track->parts = reallocf(track->parts, sizeof(struct cue_track_part *) * track->parts_count);
	assert(track->parts != NULL);
	track->parts[track->parts_count - 1] = part;

	return 0;
}

int
get_cue_track_parts_count(struct cue_track *track)
{
	assert(track != NULL);
	return (track->parts_count);
}

struct cue_track_part *
get_cue_track_part(struct cue_track *track, int index)
{
	assert(track != NULL);
	assert(index >= 0);

	if (index >= track->parts_count)
		return NULL;
	else
		return (track->parts[index]);
}

struct cue_cd *
create_cue_cd()
{
	struct cue_cd *result = calloc(1, sizeof(struct cue_cd));
	assert(result != NULL);
	return result;
}

void
destroy_cue_cd(struct cue_cd *cd)
{
	int i;

	free(cd->songwriter);
	free(cd->performer);
	free(cd->title);
	for (i = 0; i < cd->tracks_count; ++i)
		destroy_cue_track(cd->tracks[i]);
	free(cd->tracks);
	free(cd);
}

int
add_cue_track(struct cue_cd *cd, struct cue_track *track)
{
	assert(cd != NULL);
	assert(track != NULL);

	++cd->tracks_count;
	++cd->tracks_size;

	cd->tracks = reallocf(cd->tracks, sizeof(struct cue_track *) * cd->tracks_count);
	assert(cd->tracks != NULL);
	cd->tracks[cd->tracks_count - 1] = track;

	return 0;
}

int
get_cue_tracks_count(struct cue_cd *cd)
{
	assert(cd != NULL);
	return (cd->tracks_count);
}

struct cue_track *
get_cue_track(struct cue_cd *cd, int index)
{
	assert(cd != NULL);
	assert(index >= 0);

	if (index >= cd->tracks_count)
		return NULL;
	else
		return (cd->tracks[index]);
}

